package com.bjsxt.login.service.impl;

import com.bjsxt.livegoods.pojo.LoginLog;
import com.bjsxt.livegoods.pojo.ValidateCode;
import com.bjsxt.login.dao.LogMongoDao;
import com.bjsxt.login.dao.RedisDao;
import com.bjsxt.login.service.LoginService;
import com.livegoods.commons.vo.LivegoodsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * @ClassName : LoginServiceImpl
 * @Description :
 * @Author : ZWZ
 * @Date: 2021/8/27 10:24
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisDao redisDao;
    @Autowired
    private LogMongoDao logMongoDao;

    /**
     * 用户登录
     *
     * @param username 手机号
     * @param password 验证码
     * @return
     */
    @Override
    public LivegoodsResult login(String username, String password) {
        LoginLog loginLog = new LoginLog();
        loginLog.setLoginTime(new Date());
        loginLog.setUsername(username);
        loginLog.setType(LoginLog.YZM_TYPE);

        ValidateCode validateCode = redisDao.get(username);
        if (Objects.isNull(validateCode)) {
            loginLog.setSuccess(false);
            loginLog.setMessage("验证登录过期, 登录失败");
            logMongoDao.addLoginLog(loginLog);
            return LivegoodsResult.error("验证登录过期");
        }

        if (!validateCode.getCode().equals(password)) {
            loginLog.setSuccess(false);
            loginLog.setMessage("验证登录不正确, 登录失败");
            logMongoDao.addLoginLog(loginLog);
            return LivegoodsResult.error("验证登录不正确");
        }

        // 删除验证码
        redisDao.delete(username);
        loginLog.setSuccess(true);
        loginLog.setMessage("登录成功");
        logMongoDao.addLoginLog(loginLog);

        return LivegoodsResult.ok("登录成功");
    }

    @Override
    public LivegoodsResult sendYzm(String phone) {
        ValidateCode validateCode = redisDao.get(phone);
        if (Objects.nonNull(validateCode)) {
            return LivegoodsResult.ok("原验证码仍有效，请勿重复申请新的验证码");
        }

        // 生成验证码
        StringBuilder sb = new StringBuilder("");
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            sb.append(random.nextInt(10));
        }
        ValidateCode generateValidateCode = new ValidateCode();
        generateValidateCode.setPhone(phone);
        generateValidateCode.setCode(sb.toString());

        redisDao.set(phone, generateValidateCode);
        System.out.println("generateValidateCode = " + generateValidateCode);

        return LivegoodsResult.ok("验证码已发送成功，请查收");
    }
}
